package com.ruoyi.web.controller.persona;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ReceivedMessage;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.smartai.service.IDialogueService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWaClientService;
import com.ruoyi.system.service.ICustomerInfoService;
import com.ruoyi.system.service.impl.StatusCheckService;
import com.ruoyi.system.service.impl.WaURLService;
import com.ruoyi.web.controller.webSocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 客服信息
 */
@RestController
@Api("设备管理")
@RequestMapping("/persona/customer")
public class CustomerInfoController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CustomerInfoController.class);

    @Autowired
    private StatusCheckService statusCheckService;

    @Autowired
    private ICustomerInfoService waUserService;

    @Autowired
    private IWaClientService waClientService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private Environment env;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WaURLService waURLService;

//    @Autowired
//    private WebSocketServer webSocketServer;

    @Autowired
    private IDialogueService iDialogueService;

    @Value("${devicesPath.sendByIds}")
    private String sendByIds;

    @Value("${devicesPath.syncBookURL}")
    private String syncBookURL;


    @Value("${devicesPath.automessage}")
    private String autoMessage;

    @Value("${devicesPath.openwa}")
    private String openwa;

    @Value("${devicesPath.unlockURL}")
    private String unlock;

    @Value("${devicesPath.unread}")
    private String unread;

    @Value("${devicesPath.doubleSend}")
    private String doubleSend;

    @Value("${apiSevicePath.secketSendmessage}")
    private String newChatURL;


    /**
     * 获取坐席列表
     */
    @PreAuthorize("@ss.hasPermi('customer:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustomerInfo user) {
        startPage();
        List<CustomerInfo> list = waUserService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取坐席列表
     */
    @PreAuthorize("@ss.hasPermi('chat:ui:list')")
    @GetMapping("/wa/list")
    public TableDataInfo waList(String userName) {
        startPage(100);
        CustomerInfo user = new CustomerInfo();
        List<CustomerInfo> userlist = waUserService.selectUserList(user);
        return null;
    }


    /**
     * 客户端准备好了
     *
     * @param contactNumber
     * @return
     */
    @PreAuthorize("@ss.hasPermi('customer:user:query')")
    @GetMapping("/ready/{contactNumber}")
    public AjaxResult clientReady(@PathVariable String contactNumber) {
        CustomerInfo cusUser = waUserService.selectUserByNumber(contactNumber);
        cusUser.setLinkStatus("0");
        return success(waUserService.updateUser(cusUser));
    }

    /**
     * 新增坐席
     */
//    @PreAuthorize("@ss.hasPermi('customer:user:add')")
    @ApiOperation("新增客服")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "devicesId", value = "设备Id", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "devicesName", value = "设备名称", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "contactName", value = "客服名称", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "contactNumber", value = "客服账户", dataType = "String", dataTypeClass = String.class)

    })
    @Log(title = "新增客服", businessType = BusinessType.INSERT)
    @Anonymous
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CustomerInfo user) {
        if (!waUserService.checkContactNumberUnique(user)) {
            return error("新增坐席'" + user.getContactNumber() + "'失败，whatsapp账号已存在");
        }
//        SysUser u = sysUserService.selectUserByUserName(user.getUserName());
//        if (StringUtils.isNull(u)) {
//            return error("新增坐席所属用户账户不存在");
//        }
//        user.setUserId(u.getUserId());
//        user.setDeptId(u.getDeptId());
        return toAjax(waUserService.insertUser(user));
    }


    /**
     * 修改坐席
     */
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CustomerInfo user) {
//        if (StringUtils.isEmpty(user.getUserName())) {
//            return error("新增坐席所属用户账户为空");
//        }
//        SysUser u = sysUserService.selectUserByUserName(user.getUserName());
//        if (StringUtils.isNull(u)) {
//            return error("新增坐席所属用户账户不存在");
//        }
//        user.setUserId(u.getUserId());
//        user.setDeptId(u.getDeptId());
        return toAjax(waUserService.updateUser(user));
    }

    @ApiOperation("根据设备ID更新信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "devicesId", value = "设备Id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "devicesName", value = "设备名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "contactName", value = "客服名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "contactNumber", value = "客服账户", dataType = "String", dataTypeClass = String.class)

    })
    @Anonymous
    @Log(title = "根据设备ID更新信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @PutMapping("/updateDevices")
    public AjaxResult updateUserByDevicesId(@Validated @RequestBody CustomerInfo user) {
        if (StringUtils.isEmpty(user.getDevicesId())) {
            return error("设备id不能为空");
        }
        return toAjax(waUserService.updateUser(user));
    }

    /**
     * 删除坐席
     */
    @PreAuthorize("@ss.hasPermi('customer:user:remove')")
    @Log(title = "坐席管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String[] id) {
        return toAjax(waUserService.deleteUserByNumbers(id));
    }

    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @GetMapping(value = "/{id}")
    public AjaxResult getCustomer(@PathVariable String id) {
        return success(waUserService.selectChatById(id));
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('customer:user:changeStatus')")
    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @Anonymous
    public AjaxResult changeStatus(@RequestBody CustomerInfo user) {
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if (sysUser.getUserName().equals("A001")) {
            user.setTemplateId("103");
        }
        return toAjax(waUserService.updateChatStatus(user));
    }


    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping("/linkStatus")
    @Anonymous
    public AjaxResult linkStatus(@RequestBody CustomerInfo user) {
//        LoginUser loginUser = getLoginUser();
//        SysUser sysUser = loginUser.getUser();
//        if (sysUser.getUserName().equals("A001")) {
//            user.setTemplateId("103");
//        }
        return toAjax(waUserService.updateLinkStatus(user));
    }

    /**
     * 获取登录二维码
     */
    @PreAuthorize("@ss.hasPermi('customer:user:link')")
    @GetMapping("/createClient/{contactNumber}")
    public AjaxResult createClient(@PathVariable("contactNumber") String contactNumber) {

        String url = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.createClient");
        String rspStr = HttpUtils.sendGet(url + contactNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        log.info("createClient:" + rspStr);
        statusCheckService.startManualCheck(contactNumber);
        return ajax;
    }

    /**
     * 断开链接
     *
     * @param contactNumber
     * @return
     */
    @GetMapping("/disconnectedClient/{contactNumber}")
    public AjaxResult disconnectedClient(@PathVariable("contactNumber") String contactNumber) {
        CustomerInfo user = new CustomerInfo();
        user.setContactNumber(contactNumber);
        user.setLinkStatus("1");
        waUserService.updateLinkStatus(user);
        statusCheckService.cancelTask(contactNumber);
        log.info("----------------  deleteClient  deleteClient-------------------");

        String url = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.deleteClient");

        String rspStr = HttpUtils.sendGet(url + contactNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

//    /**
//     * 接收信息
//     *
//     * @param receivedMessage
//     * @return
//     */
//    @PutMapping("/received/message")
//    @Anonymous
//    public AjaxResult receivedMessage(@RequestBody ReceivedMessage receivedMessage) {
//        try {
//            String clientNumber = receivedMessage.getFromNumber();
//            CustomerChat user = waClientService.selectChatByClientNumber(clientNumber);
//            if (StringUtils.isNull(user)) {
//                logger.info("不是目标粉丝发送的消息：" + clientNumber);
//                return error("不是目标粉丝发送的消息：" + clientNumber);
//            }
//            logger.info("接收来自到粉丝的消息：" + clientNumber);
//            receivedMessage.setUserType(1);
//            receivedMessage.setType("chat");
//            webSocketServer.setMessage(receivedMessage.getToNumber(), receivedMessage);
//        } catch (Exception e) {
//            return error("发送消息失败");
//        }
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("code", "101");
//        return ajax;
//    }

    @Log(title = "客服数据导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerInfo user) {
        List<CustomerInfo> list = waUserService.selectUserList(user);
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        util.exportExcel(response, list, "whatsapp数据");
    }


    @Log(title = "客服数据导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        List<CustomerInfo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = waUserService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @Log(title = "客服数据模板", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:changeStatus')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        util.importTemplateExcel(response, "whatsapp数据");
    }


    /**
     * 群名设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:bulk')")
    @Log(title = "群名设置", businessType = BusinessType.UPDATE)
    @PostMapping("/setBulkSend")
    public AjaxResult setBulkSend(@RequestBody BulkSendName bulkSendName) {
        return toAjax(waUserService.selectToids(bulkSendName));
    }

    /**
     * apiSend设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "apiSend设置", businessType = BusinessType.UPDATE)
    @PostMapping("/apiSend")
    public AjaxResult apiSend(@RequestBody BulkSendName bulkSendName) {
        return toAjax(waUserService.selectToApi(bulkSendName));
    }


    /**
     * 回访设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "apiSend设置", businessType = BusinessType.UPDATE)
    @PostMapping("/relpyback")
    public AjaxResult relpyback(@RequestBody BulkSendName bulkSendName) {
        int res = statusCheckService.checkGroupCode(bulkSendName.getCallBackTime(), bulkSendName.getGroupCheckData());
        return toAjax(res);
    }


    /**
     * 一键重连
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "reconnect", businessType = BusinessType.UPDATE)
    @GetMapping("/reconnect")
    public AjaxResult reconnect() {
        String rspStr = waUserService.reconnect();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }


    /**
     * TeleName设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "TeleName设置", businessType = BusinessType.UPDATE)
    @PostMapping("/setTelegram")
    public AjaxResult setTelegram(@RequestBody BulkSendName bulkSendName) {
        return toAjax(waUserService.setTelegram(bulkSendName));
    }


    /**
     * 设备同步
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "TeleName设置", businessType = BusinessType.UPDATE)
    @GetMapping("/syncDevice")
    public AjaxResult syncDevice() {
        SysUser user = getLoginUser().getUser();
        return toAjax(waUserService.syncDevices(user));
    }


    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/sendByIds")
    public AjaxResult clientChat(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  newChat-------------------:" + sendByIds);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids + "&";
        // 对message进行URL编码
        String encodedMessage = URLEncoder.encode(bulkSendName.getMessage(), StandardCharsets.UTF_8.toString());
        param += "message=" + encodedMessage;
        String rspStr = HttpUtils.sendGet(sendByIds + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/transfer")
    public AjaxResult transfer(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  transfer  newChat-------------------:" + sendByIds);
        return toAjax(waClientService.updateCustomerByStatus(bulkSendName));
    }

    @PreAuthorize("@ss.hasPermi('customer:user:stopSend')")
    @PostMapping("/stopSend")
    public AjaxResult stopRun(@RequestBody BulkSendName bulkSendName){
        return toAjax(waUserService.selectById(bulkSendName.getId()));
    }

    /**
     * 同步通讯录
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "同步通讯录", businessType = BusinessType.UPDATE)
    @PostMapping("/syncBook")
    public AjaxResult syncBook(@RequestBody BulkSendName bulkSendName) {
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String url = syncBookURL + param;
        log.info("----------------  autoChat  syncBookURL-------------------:" + url);
        String rspStr = HttpUtils.sendGet(url);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    /**
     * 自动养号
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "自动养号", businessType = BusinessType.UPDATE)
    @PostMapping("/autoMessage")
    public AjaxResult autoMessage(@RequestBody BulkSendName bulkSendName) {
        log.info("----------------  autoChat  autoMessage-------------------:" + autoMessage);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String rspStr = HttpUtils.sendGet(autoMessage + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    /**
     * 开启wa
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "开启wa", businessType = BusinessType.UPDATE)
    @PostMapping("/openwa")
    public AjaxResult openwa(@RequestBody BulkSendName bulkSendName) {
        log.info("----------------  autoChat  openwa-------------------:" + openwa);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String rspStr = HttpUtils.sendGet(openwa + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    /**
     * unlock
     */
    @PreAuthorize("@ss.hasPermi('customer:user:unlock')")
    @Log(title = "unlock", businessType = BusinessType.UPDATE)
    @PostMapping("/unlock")
    public AjaxResult unlock(@RequestBody BulkSendName bulkSendName) {
        log.info("----------------  autoChat  unlock-------------------:" + unlock);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids;
        String rspStr = HttpUtils.sendGet(unlock + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }


    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/unread")
    public AjaxResult unread(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  unread-------------------:" + sendByIds);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids + "&";
        // 对message进行URL编码
        String encodedMessage = URLEncoder.encode(bulkSendName.getMessage(), StandardCharsets.UTF_8.toString());
        param += "message=" + encodedMessage;
        String rspStr = HttpUtils.sendGet(unread + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @PostMapping("/doubleSend")
    public AjaxResult doubleSend(@RequestBody BulkSendName bulkSendName) throws UnsupportedEncodingException {
        log.info("----------------  autoChat  doubleSend-------------------:" + sendByIds);
        String param = "?";
        // 假设getId()返回的是ID列表，使用String.join()将它们以逗号分隔
        String ids = String.join(",", bulkSendName.getId());
        param += "id=" + ids + "&";
        // 对message进行URL编码
        String encodedMessage = URLEncoder.encode(bulkSendName.getMessage(), StandardCharsets.UTF_8.toString());
        param += "message=" + encodedMessage;
        String rspStr = HttpUtils.sendGet(doubleSend + param);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);

        return ajax;
    }


    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/startChat/{id}")
    public AjaxResult startChat(@PathVariable("id") String[] id) {
        log.info("----------------  autoChat  startChat-------------------:"+newChatURL);
//        String rspStr = HttpUtils.sendGet(newChatURL + id);
        AjaxResult ajax = AjaxResult.success();
        int data = iDialogueService.startForCustomerIds(id,newChatURL);
        ajax.put("data", data);
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('customer:user:chat')")
    @GetMapping("/chat/list")
    public AjaxResult getAgentList() {
        AjaxResult ajax = AjaxResult.success();
        List<ChatBoxInfo> data = waUserService.getAgentList();
        ajax.put("data", data);
        return ajax;
    }

    @GetMapping("/cus/list")
    public AjaxResult selectAllName() {
        log.info("----------------  autoChat  selectAllName-------------------:"+newChatURL);
        AjaxResult ajax = AjaxResult.success();
        List<CustomerInfo> data = waUserService.selectAllName();
        ajax.put("data", data);
        return ajax;
    }


//Cannot invoke "com.ruoyi.smartai.service.IDialogueService.startForCustomerIds(String[], String)" because "this.iDialogueService" is null
}
